package com.fast.web;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

/**
 * LoginController负责打开登录页面(GET请求)和登录出错页面(POST请求)，
 * 
 * 真正登录的POST请求由Filter完成,
 * 
 * @author Tonny Luo
 */
@Controller
@RequestMapping("/login")
public class LoginController extends AbstracterController {

	@Override
	public String getRootPath() {
		return EMPTY_PATH;
	} 	
	
	@RequestMapping
	public String index() {
		logger.info("index()");
		return "/login";
	}

	@RequestMapping(value="/check",method = RequestMethod.POST)
	public ModelAndView loginCheck(String username, String password) {
		UsernamePasswordToken token = new UsernamePasswordToken(username,
				password);
		logger.info("execute()");
		// 记录该令牌
		token.setRememberMe(false);
		// subject权限对象
		Subject subject = SecurityUtils.getSubject();
		try {
			subject.login(token);
		} catch (UnknownAccountException e) {// 用户名没有找到
			model.put("err", "用户名不存在");
			return view("forward:/login");
		} catch (IncorrectCredentialsException e) {// 用户名密码不匹配
			model.put("err", "用户名密码不匹配");
			return view("forward:/login");
		} catch (AuthenticationException e) {// 其他的登录错误
			model.put("err", "用户名登录异常");
			return view("forward:/login");
		}

		// 验证是否成功登录的方法
		if (subject.isAuthenticated()) {
			return view("redirect:/system");
		}
		return view("forward:/login");
	}

	// 退出
	@RequestMapping("/logout")
	public void logout() {
		Subject subject = SecurityUtils.getSubject();
		subject.logout();
	}

}
